package com.enqualcomm.kids.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.TerminalDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.DeleteSilenceParams;
import com.enqualcomm.kids.network.socket.request.QuerySilenceParams;
import com.enqualcomm.kids.network.socket.request.UpdateSilenceParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.QuerySilenceResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.PullRefreshListView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import common.utils.DensityUtil;
import common.utils.NetUtil;
import common.utils.PromptUtil;

public class SilenceActivity extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {
    //    private ImageView title_bar_right_image;
    private TextView alarm_count_tv;
    private PullRefreshListView alarm_listview;
    private boolean isUserRefresh;
    private MyAdapter adapter;
    private List<QuerySilenceResult.Data> silenceResults;
    private View no_alarms_pop;
    private TerminallistResult.Terminal terminal;
    private String userid;
    private String userkey;
    private NetworkModel networkModel;
    Button add_silence_ibt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_silence);
        terminal = getTerminal();
        AppDefault appDefault = new AppDefault();
        userid = appDefault.getUserid();
        userkey = appDefault.getUserkey();
        networkModel = new NetworkModel();

        initView();
        initData();
    }

    private void initView() {
        //标题栏
        findViewById(R.id.title_bar_left_iv).setOnClickListener(this);
        add_silence_ibt = (Button) findViewById(R.id.add_silence_ibt);
        add_silence_ibt.setOnClickListener(this);

        //名字，头像
        QueryUserTerminalInfoResult.Data info = new UserTerminalDefault(terminal.userterminalid).getInfo();
        setupTitleIcon(info, terminal.terminalid, terminal.userterminalid, getString(R.string.s_silence_time));

        //下拉刷新listview
        alarm_listview = (PullRefreshListView) findViewById(R.id.alarm_listview);
        alarm_listview.setCanRefresh(true);
        alarm_listview.setPullRefreshListener(new PullRefreshListView.PullRefreshListener() {

            @Override
            public void onRefresh() {
                isUserRefresh = true;
                initData();
            }

            @Override
            public void onLoadMore() {

            }
        });
        adapter = new MyAdapter();
        alarm_listview.setAdapter(adapter);
        alarm_listview.setOnItemClickListener(this);
        alarm_listview.setOnItemLongClickListener(this);

        //底部显示剩余可添加数量
        TextView list_type_tv = (TextView) findViewById(R.id.list_type_tv);
        list_type_tv.setText(R.string.s_last_silence_count);
        alarm_count_tv = (TextView) findViewById(R.id.alarm_count_tv);

        no_alarms_pop = findViewById(R.id.no_alarms_pop);
        ImageView pop_iv = (ImageView) findViewById(R.id.pop_iv);
        pop_iv.setImageResource(R.drawable.silence_icon_big);
        TextView pop_tv = (TextView) findViewById(R.id.pop_tv);
        pop_tv.setText(R.string.s_no_silence);
    }


    private void initData() {
        showProgress();
        networkModel.loadDataFromServer(new SocketRequest<QuerySilenceResult>(new QuerySilenceParams(userkey, terminal.terminalid),
                new NetworkListener<QuerySilenceResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        hideProgress();
                        PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
                    }

                    @Override
                    public void onSuccess(QuerySilenceResult response) {
                        hideProgress();
                        String dateStr = getString(R.string.refresh_time) + new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date());
                        if (isUserRefresh) {
                            isUserRefresh = false;
                            alarm_listview.onRefreshComplete(dateStr);
                        } else {
                            alarm_listview.setRefreshTime(dateStr);
                        }
                        if (response.code == 0) {
                            silenceResults = response.result;
                            if (silenceResults.size() == 0) {
                                no_alarms_pop.setVisibility(View.VISIBLE);
                            } else {
                                no_alarms_pop.setVisibility(View.GONE);
                            }

                            adapter.notifyDataSetChanged();
                            new TerminalDefault(terminal.terminalid).setSilenceCount(String.valueOf(silenceResults.size()));

                            int count = 5 - silenceResults.size();
                            if (count > 0) {
                                add_silence_ibt.setVisibility(View.VISIBLE);
                            } else {
                                add_silence_ibt.setVisibility(View.INVISIBLE);
                            }
                            alarm_count_tv.setText(count + "");

                        }
                    }
                }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_left_iv:
                finish();
                break;
            case R.id.add_silence_ibt:
                // 添加静默时段
                QuerySilenceResult.Data querySilenceResult = new QuerySilenceResult.Data();
                querySilenceResult.begintime = "08:00";
                querySilenceResult.endtime = "12:00";
                querySilenceResult.isopen = 1;
                querySilenceResult.week = 62;//一、二、三、四、五

                Intent intent = new Intent(this, SilenceSettingActivity.class);
                intent.putExtra("terminal", terminal);
                intent.putExtra("silenceResult", querySilenceResult);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        Intent intent = new Intent(this, SilenceSettingActivity.class);
        intent.putExtra("terminal", terminal);
        intent.putExtra("silenceResult", silenceResults.get(position - 1));
        startActivityForResult(intent, 1);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   int position, long id) {
        new CancelTerminalDialog(this, silenceResults.get(--position).silenceid).show();
        return true;
    }

    private class CancelTerminalDialog extends Dialog {
        String silenceid;

        public CancelTerminalDialog(Context context, String silenceid) {
            super(context);
            this.silenceid = silenceid;
        }

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            this.setContentView(R.layout.dialog_cancelterminal);

            setDialogAttributes();

            initDialogView();
        }

        public void setDialogAttributes() {
            Window dialogWindow = getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();

            DisplayMetrics dm = new DisplayMetrics();
            dialogWindow.getWindowManager().getDefaultDisplay().getMetrics(dm);

            lp.width = dm.widthPixels - DensityUtil.dip2px(getContext(), 30); // 宽度

            // lp.alpha = 0.9f; // 透明度

            dialogWindow.setAttributes(lp);
            dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        public void initDialogView() {
            TextView myTerminal = (TextView) findViewById(R.id.myTerminal);
            myTerminal.setText(getString(R.string.delete));
            TextView dialog_msg_tv = (TextView) findViewById(R.id.dialog_msg_tv);
            dialog_msg_tv.setText(getString(R.string.confirm_delete));

            findViewById(R.id.sureBtn).setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View arg0, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        dismiss();
                        showProgress();
                        DeleteSilenceParams deleteSilenceParams = new DeleteSilenceParams(userkey, userid, terminal.terminalid, silenceid);
                        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(deleteSilenceParams, new NetworkListener<BasicResult>() {
                            @Override
                            public void onError(VolleyError error) {
                                hideProgress();
                                PromptUtil.toast(getContext(), R.string.app_no_connection);
                            }

                            @Override
                            public void onSuccess(BasicResult response) {

                                if (response.code == 0) {
                                    PromptUtil.toast(getContext(), R.string.delete_success);
                                    initData();
                                } else {
                                    hideProgress();
                                }
                            }
                        }));
                    }
                    return false;
                }
            });

            findViewById(R.id.cancelBtn).setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View arg0, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        dismiss();
                    }
                    return false;
                }
            });
        }
    }


    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return silenceResults == null ? 0 : silenceResults.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(SilenceActivity.this, R.layout.silence_list_item, null);
            ImageView alarm_checkbox_icon = (ImageView) view.findViewById(R.id.alarm_checkbox_icon);
            TextView alarm_textview_time = (TextView) view.findViewById(R.id.alarm_textview_time);
            TextView alarm_textview_type = (TextView) view.findViewById(R.id.alarm_textview_type);
            TextView alarm_textview_switchstate = (TextView) view.findViewById(R.id.alarm_textview_switchstate);
            CheckBox alarm_checkbox_switch = (CheckBox) view.findViewById(R.id.alarm_checkbox_switch);
            RelativeLayout alarm_item_rl = (RelativeLayout) view.findViewById(R.id.silence_rl);

            final QuerySilenceResult.Data silenceResult = silenceResults.get(position);

            if (silenceResult.isopen == 1) {//1开启 0关闭
                alarm_checkbox_switch.setChecked(true);
                int color = getResources().getColor(R.color.text1);
                alarm_textview_time.setTextColor(color);
                alarm_textview_type.setTextColor(color);
                alarm_textview_switchstate.setTextColor(color);
                alarm_checkbox_icon.setBackgroundResource(R.drawable.silence_open);
                alarm_textview_switchstate.setText(getString(R.string.alarm_switch_on));
                alarm_item_rl.setSelected(false);
            } else {
                alarm_checkbox_switch.setChecked(false);
                int color = getResources().getColor(R.color.text2);
                alarm_textview_time.setTextColor(color);
                alarm_textview_type.setTextColor(color);
                alarm_textview_switchstate.setTextColor(color);
                alarm_checkbox_icon.setBackgroundResource(R.drawable.silence_close);
                alarm_textview_switchstate.setText(getString(R.string.alarm_switch_off));
                alarm_item_rl.setSelected(true);
            }

            alarm_textview_time.setText(silenceResult.begintime + " - " + silenceResult.endtime);
            switch (silenceResult.week) {
                case 127:
                    alarm_textview_type.setText(getString(R.string.alarm_allweek));
                    break;
                case 0:
                    alarm_textview_type.setText("");
                    break;
                case 62:
                    alarm_textview_type.setText(getString(R.string.alarm_workday));
                    break;
                case 65:
                    alarm_textview_type.setText(getString(R.string.alarm_weekend));
                    break;
                default:
                    StringBuilder builder = new StringBuilder();
                    String binaryString = Integer.toBinaryString(silenceResult.week);
                    char[] weeknum = new char[7];
                    for (int i = 0; i < binaryString.length(); i++) {
                        weeknum[i] = binaryString.charAt(binaryString.length() - 1 - i);
                    }
                    if (weeknum[0] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_sunday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_sunday));
                        }
                    }
                    if (weeknum[1] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_monday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_monday));
                        }
                    }
                    if (weeknum[2] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_tuesday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_tuesday));
                        }
                    }
                    if (weeknum[3] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_wednesday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_wednesday));
                        }
                    }
                    if (weeknum[4] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_thursday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_thursday));
                        }
                    }
                    if (weeknum[5] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_firday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_firday));
                        }
                    }
                    if (weeknum[6] == '1') {
                        if (builder.length() == 0) {
                            builder.append(getString(R.string.alarm_week_saturday));
                        } else {
                            builder.append("、").append(getString(R.string.alarm_week_saturday));
                        }
                    }
                    alarm_textview_type.setText(builder.toString());
                    break;
            }

            alarm_checkbox_switch.setOnCheckedChangeListener(new onChangeListener(alarm_checkbox_icon,
                    alarm_textview_time, alarm_textview_type, alarm_textview_switchstate, position, alarm_item_rl));

            return view;
        }
    }

    private class onChangeListener implements CompoundButton.OnCheckedChangeListener {
        ImageView alarm_checkbox_icon;
        TextView alarm_textview_time;
        TextView alarm_textview_type;
        TextView alarm_textview_switchstate;
        RelativeLayout alarm_item_rl;
        int position;

        public onChangeListener(ImageView alarm_checkbox_icon, TextView alarm_textview_type,
                                TextView alarm_textview_time, TextView alarm_textview_switchstate, int position, RelativeLayout alam_itme_rl) {
            this.alarm_checkbox_icon = alarm_checkbox_icon;
            this.alarm_textview_time = alarm_textview_time;
            this.alarm_textview_type = alarm_textview_type;
            this.alarm_textview_switchstate = alarm_textview_switchstate;
            this.alarm_item_rl = alam_itme_rl;
            this.position = position;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (NetUtil.checkNet(getApplicationContext())) {
                if (isChecked) {
                    alarm_textview_time.setTextColor(getResources().getColor(R.color.text1));
                    alarm_textview_type.setTextColor(getResources().getColor(R.color.text1));
                    alarm_checkbox_icon.setBackgroundResource(R.drawable.silence_open);
                    alarm_textview_switchstate.setText(getString(R.string.alarm_switch_on));
                    alarm_textview_switchstate.setTextColor(getResources().getColor(R.color.text1));
                    alarm_item_rl.setSelected(false);

                } else {
                    alarm_textview_time.setTextColor(getResources().getColor(R.color.text2));
                    alarm_textview_type.setTextColor(getResources().getColor(R.color.text2));
                    alarm_checkbox_icon.setBackgroundResource(R.drawable.silence_close);
                    alarm_textview_switchstate.setText(getString(R.string.alarm_switch_off));
                    alarm_textview_switchstate.setTextColor(getResources().getColor(R.color.text2));
                    alarm_item_rl.setSelected(true);
                }

                QuerySilenceResult.Data silenceResult = silenceResults.get(position);
                silenceResult.isopen = isChecked ? 1 : 0;
                UpdateSilenceParams updateSilenceParams = new UpdateSilenceParams(userkey, userid, terminal.terminalid, silenceResult.begintime, silenceResult.endtime,
                        silenceResult.isopen, silenceResult.week, silenceResult.silenceid);
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(updateSilenceParams, null));

            } else {
                //没有网络，提示
                PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
                buttonView.setChecked(!isChecked);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 99) {
            initData();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }
}
